package com.heima.tlias.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.heima.tlias.controller.request.LoginRequest;
import com.heima.tlias.controller.response.UserInfoVo;
import com.heima.tlias.dao.EmpMapper;
import com.heima.tlias.pojo.Emp;
import com.heima.tlias.service.LoginService;
import com.heima.tlias.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final EmpMapper empMapper;

    @Override
    public UserInfoVo login(LoginRequest request) {
        //1. 根据用户名和密码查询员工信息
        Emp emp = empMapper.queryByUsernameAndPassword(request.getUsername(), request.getPassword());
        //2. 判断用户是否登录成功
        if (emp == null) {
            return null;
        }
        //登录成功 : 生成令牌(TOKEN)
        UserInfoVo userInfo = new UserInfoVo(emp.getId(), emp.getUsername(), emp.getName(), emp.getImage(), null);
        //生成令牌
        Map<String, Object> claims = BeanUtil.beanToMap(userInfo);
        String jwt = JwtUtil.createJwt(claims);
        //设置生成的令牌到响应实体 , 返回到客户端
        userInfo.setToken(jwt);

        return userInfo;
    }
}
